package com.zkyc.framework.common.utils;

import com.jcraft.jsch.*;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class JschUtils {

    private static final Logger log = LoggerFactory.getLogger(JschUtils.class);

    private String host;
    private String username;
    private String password;
    private int port = 22;
    private int timeOut = 6000;
    private ChannelSftp channelSftp = null;
    private Session session = null;

    public JschUtils(String host, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
    }

    public ChannelSftp getChannelSftp() {
        return channelSftp;
    }

    /**
     * 通过SFTP连接服务器
     */
    public void connectSftp() {
        try {
            if (Objects.isNull(session)) buildSession();
            channelSftp = (ChannelSftp) buildChannel(CannelType.STFP);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    public void buildSession() throws Exception {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");//新环TDH 需要
        session.setConfig(config);
        session.setTimeout(timeOut);
        session.connect();
    }

    public Channel buildChannel(String channelType) throws JSchException {
        //System.out.println("Opening Channel.");
        Channel channel = session.openChannel(channelType); // 打开通道
        channel.connect(); // 建立连接
        //System.out.println("Connected successfully to ftpHost = " + session.getHost() + ",as ftpUserName = " + session.getUserName() + ", returning: " + channel);
        return channel;
    }
    /**
     * 关闭连接
     */
    public void disconnect() {
        if (this.channelSftp != null) {
            if (this.channelSftp.isConnected()) {
                this.channelSftp.disconnect();
            }
        }
        if (this.session != null) {
            if (this.session.isConnected()) {
                this.session.disconnect();
            }
        }
    }

    /**
     * 批量下载文件
     * @param remotePath：远程下载目录
     * @param localPath：本地保存目录
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath) {
        return batchDownLoadFile(remotePath, localPath, null, null, false);
    }

    /**
     * 批量下载文件
     * @param remotePath：远程下载目录
     * @param localPath：本地保存目录
     * @param fileFormat：下载文件格式(以特定字符开头,为空不做检验)
     * @param fileEndFormat：下载文件格式(文件格式,为空不做检验)
     * @param del：下载后是否删除sftp文件
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) {
        List<String> filenames = new ArrayList<>();
        try {
            Vector<?> vector = listFiles(remotePath);
            if (vector.size() > 0) {
                //size()中包含(. 和 ..)所以实际文件数目=size-2
                log.info("本次处理文件个数不为零,开始下载...fileSize={}", vector.size()-2);
                Iterator<?> it = vector.iterator();
                while (it.hasNext()) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                    String filename = entry.getFilename();
                    SftpATTRS attrs = entry.getAttrs();
                    if(".".equals(filename) || "..".equals(filename)) {
                        continue;
                    }

                    if (!attrs.isDir()) {
                        boolean flag;
                        String localFileName = localPath + filename;
                        fileFormat = fileFormat == null ? "" : fileFormat.trim();
                        fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();
                        // 四种情况
                        if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
                            if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
                                flag = downloadFile(remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        deleteSFTP(remotePath, filename);
                                    }
                                }
                            }
                        } else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
                            if (filename.startsWith(fileFormat)) {
                                flag = downloadFile(remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        deleteSFTP(remotePath, filename);
                                    }
                                }
                            }
                        } else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
                            if (filename.endsWith(fileEndFormat)) {
                                flag = downloadFile(remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        deleteSFTP(remotePath, filename);
                                    }
                                }
                            }
                        } else {
                            flag = downloadFile(remotePath, filename, localPath, filename);
                            if (flag) {
                                filenames.add(localFileName);
                                if (flag && del) {
                                    deleteSFTP(remotePath, filename);
                                }
                            }
                        }
                    }else {
                        String newRemotePath = remotePath+ filename+ "/";
                        String newLocalPath = localPath+ filename+ "\\";
                        File fi = new File(newLocalPath);
                        if(!fi.exists()) {
                            fi.mkdirs();
                        }
                        batchDownLoadFile(newRemotePath, newLocalPath);
                    }
                }
            }
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
        }
        return filenames;
    }

    /**
     * 下载单个文件
     * @param remotePath：远程下载目录
     * @param remoteFileName：下载文件名
     * @param localPath：本地保存目录
     * @param localFileName：保存文件名
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileOutputStream fileOutput = null;
        try {
            File file = new File(localPath + localFileName);
            File path = new File(localPath);
            if(!path.exists()) {
                path.mkdirs();
            }
            fileOutput = new FileOutputStream(file);
            channelSftp.get(remotePath + remoteFileName, fileOutput);
            //System.out.println(remotePath + remoteFileName + "下载完成");
            return true;
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (null != fileOutput) {
                try {
                    fileOutput.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 上传单个文件
     * @param remotePath：远程保存目录
     * @param remoteFileName：保存文件名
     * @param localPath：本地上传目录(以路径符号结束)
     * @param localFileName：上传的文件名
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileInputStream in = null;
        try {
            createDir(remotePath);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            channelSftp.put(in, remoteFileName);
            return true;
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 批量上传文件
     * @param remotePath：远程保存目录
     * @param localPath：本地上传目录(以路径符号结束)
     * @param del：上传后是否删除本地文件
     * @return
     */
    public boolean batchUploadFile(String remotePath, String localPath, boolean del) {
        try {
            File file = new File(localPath);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile() && files[i].getName().indexOf("bak") == -1) {
                    if (this.uploadFile(remotePath, files[i].getName(), localPath, files[i].getName()) && del) {
                        deleteFile(localPath + files[i].getName());
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            this.disconnect();
        }
        return false;
    }

    /**
     * 删除本地文件
     * @param filePath
     * @return
     */
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }
        if (!file.isFile()) {
            return false;
        }
        boolean rs = file.delete();
        return rs;
    }

    /**
     * 创建目录
     * @param createPath
     * @return
     */
    public boolean createDir(String createPath) {
        try {
            if (isDirExist(createPath)) {
                this.channelSftp.cd(createPath);
                return true;
            }
            String pathArry[] = createPath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString())) {
                    channelSftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    channelSftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    channelSftp.cd(filePath.toString());
                }

            }
            this.channelSftp.cd(createPath);
            return true;
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断目录是否存在
     * @param directory
     * @return
     */
    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = channelSftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            log.error(e.getMessage());
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * 删除stfp文件
     * @param directory：要删除文件所在目录
     * @param deleteFile：要删除的文件
     */
    public void deleteSFTP(String directory, String deleteFile) {
        try {
            channelSftp.rm(directory + deleteFile);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 列出目录下的文件
     * @param directory：要列出的目录
     * @return
     * @throws SftpException
     */
    public Vector<?> listFiles(String directory) throws SftpException {
        return channelSftp.ls(directory);
    }

    public void getFileNames(String dir, List<Pair<String, String>> fileMsgs) {

        try {
            channelSftp.cd(dir);
            Vector<String> lss = channelSftp.ls("*");
            for (int i = 0; i < lss.size(); i++) {
                Object obj = lss.elementAt(i);
                if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) obj;

                    if (true && !entry.getAttrs().isDir()) {
                        fileMsgs.add(new Pair<>(channelSftp.pwd(), entry.getFilename()));
                    }
                    if (true && entry.getAttrs().isDir()) {
                        if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")) {
                            getFileNames(channelSftp.pwd() + "/" + entry.getFilename(), fileMsgs);
                        }
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * JSch，执行多条语句<
     * pty 交互式命令
     *
     * @param commands
     */

    public void shellCmd(String[] commands) {
        JSch jsch = new JSch();
        Session session = null;
        ChannelShell channelShell = null;
        try {
            channelShell = (ChannelShell) session.openChannel("shell");
            channelShell.setPty(true);
            channelShell.connect();
            try (InputStream in = channelShell.getInputStream();
                 OutputStream out = channelShell.getOutputStream();
                 PrintWriter pw = new PrintWriter(out);) {
                for (String cmd : commands) {
                    pw.println(cmd);
                }
                pw.println("exit");
                pw.flush();

                //日志返回输出
                byte[] buffer = new byte[1024];
                for (; ; ) {
                    while (in.available() > 0) {
                        int i = in.read(buffer, 0, 1024);
                        if (i < 0) {
                            break;
                        }
                        String s = new String(buffer, 0, i);
                    }
                    if (channelShell.isClosed()) {
                        //System.out.println("SSH2 Exit: " + channelShell.getExitStatus());
                        break;
                    }
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelShell != null) {
                channelShell.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     * JSch，执行多条语句
     * commond 一次命令
     *
     * @param commands
     * @return
     */
    public String execCmd(String[] commands) {
        ChannelExec channelExec = null;
        String result = "";
        for (int i = 0; i < commands.length; i++) {

            try {
                String command = commands[i];
                channelExec = (ChannelExec) session.openChannel("exec");
                channelExec.setPty(false);

                channelExec.setCommand(command);
                channelExec.connect();
                InputStream std = channelExec.getInputStream();
                InputStream error = channelExec.getErrStream();
                BufferedReader brStd = new BufferedReader(new InputStreamReader(std, StandardCharsets.UTF_8));
                BufferedReader brError = new BufferedReader(new InputStreamReader(error, StandardCharsets.UTF_8));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = brStd.readLine()) != null) {
                    if (line != null && !line.trim().isEmpty()) {
                        sb.append(line+"\r\n");
                    }
                }

                while ((line = brError.readLine()) != null) {
                    if (line != null && !line.trim().isEmpty()) {
                        sb.append(line+"\r\n");
                    }
                }
                result = sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (channelExec != null) {
                    channelExec.disconnect();
                }
            }
        }

        return result;
    }

    public String execCmd(String command) {
        return execCmd(new String[]{command});
    }

//    public static void main(String[] args) {
//        JschUtils sftpUtils = null;
//        try {
//            sftpUtils = new JschUtils("192.168.1.1", "root", "root");
//            sftpUtils.connect();
//            sftpUtils.downloadFile("/opt/","1.pdf","D:\\","1.pdf");
//            sftpUtils.batchDownLoadFile("/opt/", "D:\\11\\", "2021", null, false);
//        } catch (Exception e) {
//            log.error(e.getMessage());
//            e.printStackTrace();
//        } finally {
//            sftpUtils.disconnect();
//        }
//    }

    class CannelType {
        public static final String SESSION = "session";
        public static final String SHELL = "shell";
        public static final String EXEC = "exec";
        public static final String X11 = "x11";
        public static final String AUTH = "auth-agent@openssh.com";
        public static final String DIRECT_TCPIP = "direct-tcpip";
        public static final String FORWARDED_TCPIP = "forwarded-tcpip";
        public static final String STFP = "sftp";
        public static final String SUBSYSTEM = "subsystem";
    }

}
